<?php

namespace app\admin\controller;

use app\admin\controller\Base;
use app\admin\model\Admin;
use app\admin\model\Apply;
use app\admin\model\Applytype;
use app\admin\model\Classtype;
use app\admin\model\Course;
use app\admin\model\Coursetype;
use app\admin\model\Myclass;
use think\Request;
use think\File;

class  Myclasss extends Base
{
    /*
     * 列表
     */
    public function lists(Request $request)
    {
        $user = $this->user_info();
        //查询所有的资讯分类，
        $resource = collection(Classtype::order("sort asc")->select())->toArray();
        //给查询每个分类下的所有资讯
        foreach ($resource as $k => $v) {
            $newslist = Myclass::where(array("type" => $v['id']))->order("id desc")->paginate(10, false, [
                'path' => "/admin/Courses/lists/typeid/" . $v['id'],
                'var_page' => 'page' . $v['id'],
            ]);
            foreach ($newslist as $ks => $vs) {
                $typet = Classtype::where(array("id" => $vs['type']))->find();
                $sum = Apply::where(array("classid" => $vs['classid']))->count();
                $newslist[$ks]['sum'] = $sum;
                $newslist[$ks]['typetext'] = $typet['type_name'];
                $newslist[$ks]['start_time'] = date("Y-m-d", $vs['start_time']);
                $newslist[$ks]['end_time'] = date("Y-m-d", $vs['end_time']);
            }
            $resource[$k]['newslist'] = $newslist;
        }
        $typeid = !empty($request->route("typeid")) ? $request->route("typeid") : $resource[0]['id'];
        $data = array(
            "setting" => $this->getAllSetting(),
            "activeid" => $typeid,
            "list" => $resource,
        );
        return view("lists", $data);
    }

    //上传文件
    public function upload(Request $request)
    {
        //接收上传的文件
        $file = $this->request->file('file');
        if (!empty($file)) {
            //图片存的路径
            $imgUrl = ROOT_PATH . 'public' . DS . 'static' . DS . 'admin' . DS . 'uploads' . DS . 'news';
            // 移动到框架应用根目录/public/uploads/ 目录下
            $info = $file->validate(['size' => 1048576, 'ext' => 'jpg,png,gif'])->rule('uniqid')->move($imgUrl);
            $error = $file->getError();
            //验证文件后缀后大小
            if (!empty($error)) {
                dump($error);
                exit;
            }
            if ($info) {
                // 成功上传后 获取上传信息
                //获取图片的名字
                $imgName = $info->getFilename();
                //获取图片的路径
                $photo = $imgName;

            } else {
                // 上传失败获取错误信息
                $file->getError();
            }
        } else {
            $photo = '';
        }
        if ($photo !== '') {
            return ['code' => 1, 'msg' => '成功', 'photo' => $photo];
        } else {
            return ['code' => 404, 'msg' => '失败'];
        }
    }

    //修改
    public function update(Request $request)
    {
        $user = $this->user_info();
        $id = $request->get("id");
        $data = array(
            "setting" => $this->getAllSetting(),
            "list" => Classtype::select(),
            "data" => Myclass::where(array("id" => $id))->find(),
        );
        return view("update", $data);
    }

    public function toUpdate(Request $request)
    {
        $user = $this->user_info();
        $data = $request->post();
        $old_status = $data['old_status'];
        unset($data['old_status']);
        if ($old_status != 3) {
            // 查询班级中的学生
            $users = Apply::where('classid=' . $data['classid'] . ' and status=2')->select();
            // 查询班级的开班和毕业时间
            $class = Myclass::where('classid=' . $data['classid'])->find();
            foreach ($users as $k => $v) {
                $sex = $v['sex'] == '1' ? '男' : '女';
                $certificate_time = time();
                // 给班级用户进行颁发证书
                $certificate_photo = $this->GenerateCertificate($v['certificate_number'], $v['username'], $sex, $v['idcard'], $v['course'], $class['start_time'], $class['end_time'], $v['identification_photo'], $certificate_time);
                Apply::where('id=' . $v['id'])->update(array('certificate_photo' => $certificate_photo, 'certificate_time' => $certificate_time));

            }
        }
        $data["start_time"] = strtotime($data["start_time"]);
        $data["end_time"] = strtotime($data["end_time"]);
        $data['update_time'] = time();
        if (Myclass::update($data)) {
            $this->success("修改成功", "Myclasss/lists?typeid=" . $request->post('type'));
        } else {
            $this->error("修改失败");
        }

    }

    //删除
    public function deletes(Request $request)
    {
        $user = $this->user_info();
        if (Myclass::destroy($request->post('id'))) {
            $this->success("删除成功", "Myclasss/lists?typeid=" . $request->post('typeid'));
        } else {
            $this->error("删除失败");
        }
    }

    //修改状态
    public function setStatus(Request $request)
    {
        $data = $request->post();
        if (Course::update($data)) {
            $this->success("成功");
        } else {
            $this->error("失败");
        }
    }
    //------------------------------------------------------------------------------------------------------------------
    //资讯分类列表
    public function type_list()
    {
        $user = $this->user_info();
        $resource = collection(Classtype::order("sort asc")->select())->toArray();

        foreach ($resource as $k => $v) {
            $sum = Myclass::where(array("type" => $v['id']))->count();
            $resource[$k]['sum'] = $sum;
            $courseRs = Course::where(array("id" => ['in', $v['course']]))->select();
            $courseAr = array();
            foreach ($courseRs as $ks => $vs) {
                $courseAr[] = $vs['name'];
            }
            $resource[$k]['coursetext'] = implode(",", $courseAr);

        }
        $data = array(
            "setting" => $this->getAllSetting(),
            "list" => $resource,
        );
        return view("typelist", $data);
    }

    //添加
    public function type_addform()
    {
        $user = $this->user_info();
        $course = Course::order("sort asc")->select();
        $data = array(
            "setting" => $this->getAllSetting(),
            "course" => $course,
        );
        return view("type_addform", $data);
    }

    public function type_add(Request $request)
    {
        //接收所有的请求数据，数组：多个数据的集合
        $data = $request->post();
        // 创建数组元素
        $data['create_time'] = time();
        $data['update_time'] = time();
        $res = Classtype::insert($data);  //执行数据库命令
        //返回结果的判断
        if ($res) {
            $this->success("添加成功", "Myclasss/type_list");
        } else {
            $this->error("添加失败", "Myclasss/type_addform");
        }
    }

    //删除分类
    public function type_deletes(Request $request)
    {
        $user = $this->user_info();
        $id = $request->post('id');
        //删除分类的时先去新闻标中查看该分类下是否有新闻，如果有则不允许删除
        $sum = Myclass::where(array("type" => $id))->count();
        if ($sum > 0) {
            $this->error("该分类有课程，请将课程修改到其他分类或删除该分类下的所有课程之后再删除。");
            exit();
        }
        //如果该分类下没有新闻则直接删除
        if (Classtype::destroy($id)) {
            $this->success("删除成功", "Myclasss/type_list");
        } else {
            $this->error("删除失败");
        }
    }

    //修改分类状态
    public function setTypeStatus(Request $request)
    {
        $user = $this->user_info();
        if (Classtype::update($request->post())) {
            $this->success("成功", "Myclasss/type_list");
        } else {
            $this->error("失败");
        }
    }

    //修改分类
    public function type_update(Request $request)
    {
        $user = $this->user_info();
        $id = $request->get("id");
        $course = Course::order("sort asc")->select();
        $data = array(
            "setting" => $this->getAllSetting(),
            "data" => Classtype::where(array("id" => $id))->find(),
            "course" => $course,
        );
        return view("type_update", $data);
    }

    public function type_toUpdate(Request $request)
    {
        $user = $this->user_info();
        $data = $request->post();
        $data['update_time'] = time();
        if (Classtype::update($data)) {
            $this->success("修改成功", "Myclasss/type_list");
        } else {
            $this->error("修改失败");
        }

    }

    //搜索班级
    public function search()
    {
        $user = $this->user_info();
        $classtype = Classtype::order("sort asc")->select();
        $data = array(
            "setting" => $this->getAllSetting(),
            "classtype" => $classtype,
        );
        return view("search", $data);
    }

    //去搜索学员
    public function toSearch(Request $request)
    {
        $data = $request->post();
        $where = array();
        /*
         *             classid: $("#classid").val(),          //班级编号
                       type:$("#type").val(),                   //班级类型
                       status:$("#status").val(),                   //班级类型
                       teacher:$("#phone").val(),         //老师
                       author:$("#idcard").val(),          //添加者
                       "start_time":$("#province").val(), //开班时间
                       "end_time":$("#city").val(),         //毕业时间
        */
        if (!empty($data["classid"])) {
            $where['classid'] = ['like', "%" . $data['classid'] . "%"];
        }
        if (!empty($data["type"])) {
            $where['type'] = $data['type'];
        }
        if (!empty($data["status"])) {
            $where['status'] = $data['status'];
        }
        if (!empty($data["teacher"])) {
            $where['teacher'] = ['like', "%" . $data['teacher'] . "%"];
        }
        if (!empty($data["author"])) {
            $where['author'] = ['like', "%" . $data['author'] . "%"];
        }
        if (!empty($data["start_time"])) {
            $where['start_time'] = strtotime($data['start_time']);
        }
        if (!empty($data["end_time"])) {
            $where['end_time'] = strtotime($data['end_time']);
        }
//        $this->success(json_encode($where));
        $list = Myclass::where($where)->select();
        $str = "";
        if (!empty($list)) {
            foreach ($list as $k => $v) {
                $type = Classtype::where(array("id" => $v['type']))->find();
                $status = "";
                switch ($v['status']) {
                    case 1 :
                        $status = "<span style=\"color:#d9534f\">待上课</span>";
                        break;
                    case 2 :
                        $status = "<span style=\"color:#f8ac59\">上课中</span>";
                        break;
                    case 3 :
                        $status = "<span style=\"color:green\">已毕业</span>";
                        break;
                }
                $str .= "<tr>";
                $str .= "<td>" . $v['classid'] . "</td>";
                $str .= "<td>" . $type['type_name'] . "</td>";
                $str .= "<td>" . $v['teacher'] . "</td>";
                $str .= "<td>" . date("Y-m-d", $v['start_time']) . "</td>";
                $str .= "<td>" . date("Y-m-d", $v['end_time']) . "</td>";
                $str .= "<td>" . $v['author'] . "</td>";
                $str .= "<td>" . $status . "</td>";
                $str .= "<td class=\"tools\"><a onclick='detail(" . $v['id'] . ")'><i class='fa fa-eye'></i></a> <a onclick='updates(" . $v['id'] . ")'><i class=\"fa fa-pencil\" style=\"color:#19a9d5\"></i></a> <a class=\"del\" ><i class=\"fa fa-trash\" onclick='del(" . $v['id'] . "," . $v['type'] . ")' style=\"color:#19a9d5\"></i></a></td>";
                $str .= "</tr>";
            }
            $this->success($str);
        } else {
            $this->error("<tr><td colspan=''>未查到数据</td></tr>");
        }

    }

    /*---------------------------*/
    public function addclass()
    {
        $user = $this->user_info();
        $ct = Classtype::order("sort asc")->select();
        $data = array(
            "setting" => $this->getAllSetting(),
            "list" => $ct,
        );
        return view("addclass", $data);
    }

    public function class_add(Request $request)
    {
        $user = $this->user_info();
        //接收所有的请求数据，数组：多个数据的集合
        $data = $request->post();
        $data["start_time"] = strtotime($data["start_time"]);
        $data["end_time"] = strtotime($data["end_time"]);
        // 创建数组元素
        $data['author'] = $user['username'];
        $data['create_time'] = time();
        $data['update_time'] = time();
        $res = Myclass::insert($data);  //执行数据库命令
        //返回结果的判断
        if ($res) {
            $this->success("添加成功", "Myclasss/lists");
        } else {
            $this->error("添加失败", "Myclasss/class_add");
        }
    }

    //-------------------------------------
    /*
 * 列表
 */
    public function classStudent(Request $request)
    {
        $user = $this->user_info();
        $data = $request->get();
        //查询所有的报名
        $newslist = Apply::where(array("classid" => $data['classid']))->order("id desc")->select();
        foreach ($newslist as $ks => $vs) {
            $type = Applytype::where(array('id' => $vs['type']))->find();
            $newslist[$ks]['typetext'] = $type['type_name'];
        }
        $class = Myclass::where(array("status" => ['not in', "3"]))->select();
        $datas = array(
            "setting" => $this->getAllSetting(),
            "newslist" => $newslist,
            "class" => $class,
            "classid" => $data['classid'],
        );
        return view("classStudent", $datas);
    }

    /*
     *上传学生证件照
     */
    public function upload_identification(Request $request)
    {
        //接收上传的文件
        $file = $this->request->file('file');
        if (!empty($file)) {
            //图片存的路径
            $imgUrl = ROOT_PATH . 'public' . DS . 'static' . DS . 'admin' . DS . 'uploads' . DS . 'student';
            // 移动到框架应用根目录/public/uploads/ 目录下
            $info = $file->validate(['size' => 1048576, 'ext' => 'jpg,png,gif'])->rule('uniqid')->move($imgUrl);
            $error = $file->getError();
            //验证文件后缀后大小
            if (!empty($error)) {
                dump($error);
                exit;
            }
            if ($info) {
                //获取图片的名字
                $imgName = $info->getFilename();
                //获取图片的路径
                $photo = $imgName;
            } else {
                // 上传失败获取错误信息
                $file->getError();
            }
        } else {
            $photo = '';
        }
        if ($photo !== '') {
            return ['code' => 1, 'msg' => '成功', 'photo' => $photo];
        } else {
            return ['code' => 404, 'msg' => '失败'];
        }
    }

    /*
     * 上传学生信息
     * */
    public function AddCertificate(Request $request)
    {
        $id = $request->post('id');
        $number = $request->post('number');
        $photo = $request->post('photo');
        // 进行添加信息
        $res = Apply::where('id=' . $id)->update(array('certificate_number' => $number, 'identification_photo' => $photo));
        if ($res) {
            $this->success('添加成功', "Myclasss/classstudent");
        } else {
            $this->error('添加失败');
        }

    }

    /*
     * 生成证书
     * */
    public function GenerateCertificate($certificate_number, $username, $sex, $idcard, $course, $start_time, $end_time, $identification_photo, $certificate_time)
    {
        // 课时计算
        $period = ($end_time - $start_time) / 60 / 60;
        // 模板路径
        $muban_url = $_SERVER['DOCUMENT_ROOT'] . '/static/admin/certificate/certificate.png';
        $user_url = '/static/admin/certificate/' . date('Ymd', time()) . '/' . $certificate_number . '.png';
        // 字体路径
        $font = $_SERVER['DOCUMENT_ROOT'] . '/static/admin/fonts/simhei.ttf';
        // 将信息写入模板
        if ($certificate_number != '') {

            // 写入证件照片
            $jpegHeadimg = imagecreatefromjpeg($_SERVER['DOCUMENT_ROOT'] . $identification_photo);
            $jpegSmallHeadimg = imageCreatetruecolor(130, 180);
            imagecopyresized($jpegSmallHeadimg, $jpegHeadimg, 0, 0, 0, 0, 130, 180, imagesx($jpegHeadimg), imagesy($jpegHeadimg));

        }
        /*******合并图片，将头像放置背景图中*******/
        //读取背景图
        $pngBackground = imagecreatefrompng($muban_url);
        //创建一个新的，和背景图一样大的画布
        $pngUser = imageCreatetruecolor(imagesx($pngBackground), imagesy($pngBackground));
        //为真彩色画布创建白色背景，再设置为透明
        $color = imagecolorallocate($pngUser, 255, 255, 255);
        imagefill($pngUser, 0, 0, $color);
        imageColorTransparent($pngUser, $color);
        //背景图压到新画布上
        imagecopyresampled($pngUser, $pngBackground, 0, 0, 0, 0, imagesx($pngBackground), imagesy($pngBackground), imagesx($pngBackground), imagesy($pngBackground));
        if ($certificate_number != '') {
            //证件照压到新画布上
            imagecopymerge($pngUser, $jpegSmallHeadimg, 205, 1630, 0, 0, imagesx($jpegSmallHeadimg), imagesy($jpegSmallHeadimg), 100);
        }
        //图片写入学生证书编号
        if ($certificate_number != '') {
            $white = imagecolorallocate($pngBackground, 0, 0, 0);//字体颜色
            imageTTFText($pngUser, 22, 0, 690, 920, $white, $font, $certificate_number);
        }
        //图片写入学生证书工种
        if ($course != '') {
            $white = imagecolorallocate($pngBackground, 0, 0, 0);//字体颜色
            imageTTFText($pngUser, 16, 0, 560, 1380, $white, $font, $course);
        }
        //图片写入学生姓名
        if ($username != '') {
            $white = imagecolorallocate($pngBackground, 0, 0, 0);//字体颜色
            imageTTFText($pngUser, 22, 0, 700, 1615, $white, $font, $username);
        }
        //图片写入学生性别
        if ($sex != '') {
            $white = imagecolorallocate($pngBackground, 0, 0, 0);   //字体颜色
            imageTTFText($pngUser, 22, 0, 700, 1705, $white, $font, $sex);
        }
        //图片写入学生身份证号
        for ($i = 0; $i < mb_strlen($idcard); $i++) {
            $num = substr($idcard, $i, 1);
            $white = imagecolorallocate($pngBackground, 0, 0, 0);   //字体颜色
            imageTTFText($pngUser, 22, 0, 560 + $i * 19, 1855, $white, $font, $num);
        }
        //图片写入学生发证日期
        $add_time_y = date('Y', $certificate_time);
        $white = imagecolorallocate($pngBackground, 0, 0, 0);   //字体颜色
        imageTTFText($pngUser, 18, 0, 240, 2090, $white, $font, $add_time_y);
        $add_time_m = date('m', $certificate_time);
        $white = imagecolorallocate($pngBackground, 0, 0, 0);   //字体颜色
        imageTTFText($pngUser, 18, 0, 325, 2090, $white, $font, $add_time_m);
        $add_time_d = date('d', $certificate_time);
        $white = imagecolorallocate($pngBackground, 0, 0, 0);   //字体颜色
        imageTTFText($pngUser, 18, 0, 385, 2090, $white, $font, $add_time_d);
        //图片写入学生培训的开始日期
        if ($start_time != '') {
            $start_time_y = date('Y', $start_time);
            $white = imagecolorallocate($pngBackground, 0, 0, 0);   //字体颜色
            imageTTFText($pngUser, 18, 0, 510, 2087, $white, $font, $start_time_y);
            $start_time_m = date('m', $start_time);
            $white = imagecolorallocate($pngBackground, 0, 0, 0);   //字体颜色
            imageTTFText($pngUser, 18, 0, 595, 2087, $white, $font, $start_time_m);
            $start_time_d = date('d', $start_time);
            $white = imagecolorallocate($pngBackground, 0, 0, 0);   //字体颜色
            imageTTFText($pngUser, 18, 0, 650, 2087, $white, $font, $start_time_d);
        }
        // 图片写入学生的培训结束日期
        if ($end_time != '') {
            $end_time_y = date('Y', $end_time);
            $white = imagecolorallocate($pngBackground, 0, 0, 0);   //字体颜色
            imageTTFText($pngUser, 18, 0, 723, 2087, $white, $font, $end_time_y);
            $end_time_m = date('m', $end_time);
            $white = imagecolorallocate($pngBackground, 0, 0, 0);   //字体颜色
            imageTTFText($pngUser, 18, 0, 805, 2087, $white, $font, $end_time_m);
            $end_time_d = date('d', $end_time);
            $white = imagecolorallocate($pngBackground, 0, 0, 0);   //字体颜色
            imageTTFText($pngUser, 18, 0, 860, 2087, $white, $font, $end_time_d);
        }

        // 图片写入学生的培训课程
        if ($course != '') {
            if (mb_strlen($course) > 26) {
                $kecheng = '';
                for ($s = 0; $s < mb_strlen($course) / 26; $s++) {
                    $kecheng .= substr($course, $s * 26, 26) . PHP_EOL;
                }
            } else {
                $kecheng = $course;
            }
            $white = imagecolorallocate($pngBackground, 0, 0, 0);   //字体颜色
            imageTTFText($pngUser, 12, 0, 130, 2370, $white, $font, $kecheng);
        }
        // 图片写入学生的培训学时
        if ($course != '') {
            $white = imagecolorallocate($pngBackground, 0, 0, 0);   //字体颜色
            imageTTFText($pngUser, 16, 0, 295, 2375, $white, $font, $period);
        }
        $white = imagecolorallocate($pngBackground, 0, 0, 0);   //字体颜色
        imageTTFText($pngUser, 16, 0, 380, 2375, $white, $font, '合格');

        //图片写入到文件中
        // 判断是否存在文件
        is_dir($_SERVER['DOCUMENT_ROOT'] . '/static/admin/certificate/' . date('Ymd', time())) or mkdir($_SERVER['DOCUMENT_ROOT'] . '/static/admin/certificate/' . date('Ymd', time()));
        ImageJpeg($pngUser, $_SERVER['DOCUMENT_ROOT'] . $user_url);
        imagedestroy($pngUser);
        return $user_url;

    }

    /**
     * @name 判断是否PNG图片
     * @author xiaoma
     * @time 2018年3月12日11:24:27
     */
    function isPng($pngPath)
    {
        $size = getimagesize($pngPath);
        $file_extension = strtolower(substr(strrchr($pngPath, '.'), 1));
        if ('image/jpg' != $size['mime'] || $file_extension != 'jpg' || $file_extension != 'jpeg') {
            return false;
        } else {
            return true;
        }
    }
}
